import React, {useEffect, useRef, useState} from "react";
import {ProColumns, ProTable} from "@ant-design/pro-components";
import {IncomeLogItem} from "@/pages/IncomeLogs/data";
import {Avatar, message, Popconfirm} from "antd";
import {DeleteOutlined, EditOutlined} from "@ant-design/icons";
import {ActionType} from "@ant-design/pro-table";
import {deleteIncomeLog, queryIncomeLog, updateIncomeLog} from "@/pages/IncomeLogs/service";
import dayjs from "dayjs";
import {useEmotionCss} from "@ant-design/use-emotion-css";
import UpdateForm from "@/pages/IncomeLogs/components/UpdateForm";

/**
 * 删除节点
 *
 * @param record
 */
const handleSingleRemove = async (record: IncomeLogItem) => {
  const hide = message.loading('正在删除');
  try {
    const res = await deleteIncomeLog({
      key: record.id,
    });
    hide();
    if (res) {
      if (res.status === 'done') {
        message.success(res.message);
        return true;
      } else {
        message.error(res.message);
        return false;
      }
    } else {
      message.error('请求超时，请稍后重试');
      return false;
    }
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

/**
 * 更新节点
 *
 * @param fields
 * @param currentRow
 */

const handleUpdate = async (fields: any, currentRow?: IncomeLogItem) => {
  const hide = message.loading('正在修改');

  try {
    const res = await updateIncomeLog({
      id: currentRow?.id,
      ...fields,
    });
    if(res && res.status === "done" ){
      hide();
      message.success(res.message);
      return true;
    }else {
      hide()
      message.error(res.message);
      return false;
    }
  } catch (error) {
    hide();
    message.error('更新失败，请重试！');
    return false;
  }
};

export type Props = {
  update: boolean;
};

const IncomeLogs: React.FC<Props> = (props: {update: boolean}) => {
  const actionRef = useRef<ActionType>();
  const moneyClassName = useEmotionCss(() => {
    return {
      color: "red"
    };
  });

  /** 更新窗口的弹窗 */
  const [currentRow, setCurrentRow] = useState<IncomeLogItem>();
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);

  // 更新流水
  useEffect(() => {
    actionRef.current?.reload()
  }, [props.update]);

  const columns: ProColumns<IncomeLogItem>[] = [
    {
      title: "id",
      dataIndex: "id",
      hideInSearch: true,
      hideInTable: true
    },
    {
      title: "日期",
      dataIndex: "date",
      valueType: "text",
      align: "center",
      hideInSearch: true,
      width: 100,
      render: (_, record) =>{
        if (record.date){
          return record.date
        }return null
      }
    },
    {
      title: "时间",
      dataIndex: "time",
      valueType: "time",
      align: "center",
      hideInSearch: true,
      width: 50,
      render: (_, record)=>(
        dayjs(record.time).format("HH:mm")
      )
    },
    {
      title: "分类",
      dataIndex: "type",
      valueType: "text",
      align: "center",
      hideInSearch: true,
      render: (_, record)=> {
        return (
          <>
            <Avatar size={"small"} src={"/static/icons/" + record.incomeType?.icon}/> {record.incomeType?.name}
          </>
        )
      }
    },
    {
      title: "金额",
      dataIndex: "money",
      valueType: "money",
      align: "right",
      hideInSearch: true,
      className: moneyClassName
    },
    {
      title: "备注",
      dataIndex: "remark",
      valueType: "text",
      align: "left",
    },
    {
      title: "",
      valueType: "option",
      align: "right",
      width: 30,
      render: (_, record)=>[
        <a
          style={{color: "gray"}}
          key={"update"}
          title={"修改流水"}
          onClick={()=>{
            setCurrentRow(record)
            handleUpdateModalVisible(true)
          }}
        ><EditOutlined/></a>,
        <Popconfirm key="popconfirm" title={`确认删除吗?`} okText="是" cancelText="否" onConfirm={async () => {
          const success = await handleSingleRemove(record);
          if (success) {
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}>
          <a style={{color: "gray"}} title={"删除流水"} ><DeleteOutlined /></a>
        </Popconfirm>
      ]
    },
  ];
  return (
    <>
      <ProTable
        scroll={{ y: `calc(100vh - 260px)`, x: `max-content` }}
        defaultSize={"small"}
        actionRef={actionRef}
        columns={columns}
        rowKey={"id"}
        search={false}
        headerTitle={<b style={{color: "red"}}>收入流水</b>}
        options={false}
        request={queryIncomeLog}
        pagination={{defaultPageSize: 10, pageSizeOptions:[10, 20, 100, 1000, 10000], showSizeChanger: true}}
      />
      <UpdateForm
        onCancel={()=>{
          handleUpdateModalVisible(false)
          setCurrentRow(undefined)
          actionRef.current?.reload()
        }}
        onSubmit={async (value)=>{
          const success = await handleUpdate(value, currentRow);
          if (success){
            handleUpdateModalVisible(false)
            setCurrentRow(undefined)
            // 更新数据
            actionRef.current?.reload()
          }
        }}
        modalVisible={updateModalVisible}
        values={currentRow || {}}
      />
    </>
  )
}
export default IncomeLogs;
